package com.amc.framework.exception;

import com.amc.common.utils.ServletUtils;
import com.amc.common.utils.StringUtils;
import com.amc.framework.web.domain.AjaxResult;
import com.amc.framework.web.domain.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;


/**
 * 全局异常处理器
 *
 * @author ZhangXX
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);


    /**
     * 请求方式不支持
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public AjaxResult handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException e,
                                                          HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',不支持'{}'请求", requestURI, e.getMethod());
        return AjaxResult.error(e.getMessage());
    }

    /**
     * 业务异常
     */
    @ExceptionHandler(BusinessException.class)
    public Object handleServiceException(BusinessException e, HttpServletRequest request) {
        log.error(e.getMessage(), e);
        if (ServletUtils.isAjaxRequest(request)) {
            return AjaxResult.error(e.getMessage());
        } else {
            return new ModelAndView("error/business", "errorMessage", e.getMessage());
        }
    }

    /**
     * 对外提供服务异常
     */
    @ExceptionHandler(ServiceException.class)
    public R handleServiceException(ServiceException e, HttpServletRequest request)
    {
        log.error(e.getMessage(), e);
        Integer code = e.getCode();
        return StringUtils.isNotNull(code) ? R.fail(code, e.getMessage()) : R.fail(e.getMessage());
    }

    /**
     * 自定义验证异常
     */
    @ExceptionHandler(value = {BindException.class, ValidationException.class, MethodArgumentNotValidException.class})
    public AjaxResult handleParameterVerificationException(Exception e) {
        log.error(" handleParameterVerificationException has been invoked", e);
        String msg = null;
        // BindException
        if (e instanceof BindException) {
            log.error(e.getMessage(), e);
            msg = ((BindException) e).getAllErrors().get(0).getDefaultMessage();
            // MethodArgumentNotValidException
        } else if (e instanceof MethodArgumentNotValidException) {
            log.error(e.getMessage(), e);
            BindingResult bindingResult = ((MethodArgumentNotValidException) e).getBindingResult();
            msg = bindingResult.getFieldError().getDefaultMessage();
            // ValidationException 的子类异常ConstraintViolationException
        } else if (e instanceof ConstraintViolationException) {
            log.error(e.getMessage(), e);
            msg = e.getMessage();
            if (msg != null) {
                int lastIndex = msg.lastIndexOf(':');
                if (lastIndex >= 0) {
                    msg = msg.substring(lastIndex + 1).trim();
                }
            }
            // ValidationException 的其它子类异常
        } else {
            log.error(e.getMessage(), e);
            msg = e.getMessage();
        }
        return AjaxResult.error(msg);
    }

    /**
     * 系统异常
     */
    @ExceptionHandler(Exception.class)
    public AjaxResult handleException(Exception e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',发生系统异常.", requestURI, e);
        return AjaxResult.error(e.getMessage());
    }


}
